package net.jsoft.platform.schedule.job;

import java.net.InetAddress;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import net.jsoft.platform.core.util.spring.SpringUtil;
import net.jsoft.platform.schedule.entity.ScheduleLog;
import net.jsoft.platform.schedule.repository.ScheduleLogRepository;

@Component
public abstract class BaseJob implements Job, ApplicationListener<EmbeddedServletContainerInitializedEvent>
{
    private static final Logger logger = LogManager.getLogger();

    private static int serverPort;

    @Override
    public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event)
    {
        serverPort = event.getEmbeddedServletContainer().getPort();

    }

    public int getPort()
    {
        return serverPort;
    }

    public void execute(JobExecutionContext context) throws JobExecutionException
    {
        String host = null;
        JobDetail job = context.getJobDetail();
        ScheduleLogRepository repository = SpringUtil.getBean("scheduleLogRepository", ScheduleLogRepository.class);
        Date d = new Date();
        try
        {
            host = InetAddress.getLocalHost().getHostAddress();
            JobDataMap dataMap = job.getJobDataMap();
            String ipData = dataMap.getString("ip");
            String portData = dataMap.getString("port");
            if (host.equals(ipData) && StringUtils.isNotEmpty(portData) && this.getPort() == Integer.parseInt(portData))
            {
                logger.info("=====BaseJob=====" + host + ":" + this.getPort() + " 执行自动任务" + job.getKey());
                System.out.println("=====BaseJob=====" + host + ":" + this.getPort() + " 执行自动任务" + job.getKey());
                doExecute(context);
                repository.save(new ScheduleLog(host, this.getPort() + "", job.getKey().getName(), d, 1));
            }
            else
            {
                System.out.println("=====BaseJob=====" + host + ":" + this.getPort() + " 未执行自动任务（" + ipData + ":" + portData + ")" + job.getKey());
                logger.info("=====BaseJob=====" + host + ":" + this.getPort() + " 未执行自动任务（" + ipData + ":" + portData + ")" + job.getKey());
                repository.save(new ScheduleLog(host, this.getPort() + "", job.getKey().getName(), d, 0));
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            repository.save(new ScheduleLog(host, this.getPort() + "", job.getKey().getName(), d, 2));
            System.out.println("=====BaseJob=====" + host + ":" + this.getPort() + " 异常执行自动任务" + job.getKey());
            logger.error("=====BaseJob=====" + host + ":" + this.getPort() + " 异常执行自动任务" + job.getKey());
        }

    }

    public abstract void doExecute(JobExecutionContext context) throws JobExecutionException;
}